<?php

namespace App\Console\Commands;

use App\Library\Logic\CouponLogic;
use App\Library\Logic\CouponUserRelatedLogic;
use App\Library\Logic\ShopUserLogic;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;

class RegCouponCommand extends Command
{
    /**
     * 指定用户领取优惠券
     *
     * @var string
     */
    protected $signature = 'command:regCoupon {serialNumber}';

    /**
     * 指定用户领取优惠券
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $id = $this->argument('serialNumber');
        if (empty($id) || (int)$id <= 0) return;
        $shopUser = ShopUserLogic::detail($id, ['userId', 'userType']);
        if (is_null($shopUser) || $shopUser->user_type !== 2) return;
        $list = CouponLogic::query()->where([
            'status' => 1,
            'get_condition' => 1,
            'is_system' => 1,
        ])->where(function (Builder $query) {
            $query->whereNull('start_at')->orWhere('start_at', '<', now()->toDateTimeString());
        })->where(function (Builder $query) {
            $query->whereNull('end_at')->orWhere('end_at', '>', now()->toDateTimeString());
        })->orderBy('sort')->orderByDesc('created_at')->get(['id', 'receive_count']);
        foreach ($list as $v) {
            $where = ['userId' => $id, 'couponId' => $v->id];
            if (!CouponUserRelatedLogic::existsByWhere($where)) {
                CouponUserRelatedLogic::insertForModel($where);
                $v->receive_count++;
                $v->save();
            }
        }
    }
}
